import { useState, useRef, useEffect } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import Navbar from '../../compoents/Navbar'
import { uploadSingleFile } from '../../utils/mockOssUpload'
import type { UploadResult, UploadStatus } from '../../utils/mockOssUpload'
import { UploadController } from '../../utils/ossUpload'
import { generateFileName } from '../../utils/ossConfig'
import type { RootState } from '../../store/store'
import { selectArchive } from '../../store/UseStateList'
import styles from './index.module.css'

function Index() {
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const [searchParams] = useSearchParams()
  const archivesList = useSelector((state: RootState) => state.UseStateList.archivesList)
  const [inputValue, setInputValue] = useState('')
  const [isSubmitted, setIsSubmitted] = useState(false)
  const [uploadedImages, setUploadedImages] = useState<string[]>([])
  const [uploadResults, setUploadResults] = useState<UploadResult[]>([])
  const [uploadStatuses, setUploadStatuses] = useState<{ [key: number]: UploadStatus }>({})
  const [isUploading, setIsUploading] = useState(false)
  const [uploadSuccessCount, setUploadSuccessCount] = useState(0)
  const [uploadErrors, setUploadErrors] = useState<{ [key: number]: string }>({})
  const [uploadControllers, setUploadControllers] = useState<{ [key: number]: UploadController }>({})
  const [chatMessages, setChatMessages] = useState<Array<{
    id: string
    type: 'user' | 'doctor'
    content: string
    images?: string[]
    timestamp: number
  }>>([])
  const [selectedImage, setSelectedImage] = useState<string | null>(null)
  const [showUploadSection, setShowUploadSection] = useState(true)
  const [showFileSelection, setShowFileSelection] = useState(false)
  const [currentSelectedArchiveId, setCurrentSelectedArchiveId] = useState<string | null>(null)
  const [showTriageResult, setShowTriageResult] = useState(false)
  const [showRecommendations, setShowRecommendations] = useState(false)
  const uploadContainerRef = useRef<HTMLDivElement>(null)
  const chatContainerRef = useRef<HTMLDivElement>(null)

  // 检查URL参数，如果包含showFileSelection=true，则直接显示档案选择界面
  useEffect(() => {
    const showFileSelectionParam = searchParams.get('showFileSelection')
    if (showFileSelectionParam === 'true') {
      setShowFileSelection(true)
      setShowUploadSection(false)
      setIsSubmitted(true)
      
      // 添加医生询问消息
      const doctorMessage = {
        id: `doctor_ask_${Date.now()}`,
        type: 'doctor' as const,
        content: '请问您想为以下哪位患者咨询？',
        timestamp: Date.now()
      }
      setChatMessages([doctorMessage])
    }
  }, [searchParams])

  const handleBack = () => {
    navigate(-1)
  }

  const handleSubmit = () => {
    if (inputValue.trim().length < 5) {
      alert('请输入至少5个字符描述病情')
      return
    }
    if (inputValue.trim().length > 500) {
      alert('描述不能超过500个字符')
      return
    }
    
    // 添加用户消息到聊天记录
    const userMessage = {
      id: `user_${Date.now()}`,
      type: 'user' as const,
      content: inputValue,
      timestamp: Date.now()
    }
    setChatMessages(prev => [...prev, userMessage])
    
    // 提交成功，显示上传界面
    setIsSubmitted(true)
    console.log('提交的病情描述:', inputValue)
    
    // 延迟滚动到上传区域，确保DOM已更新
    setTimeout(() => {
      if (uploadContainerRef.current) {
        uploadContainerRef.current.scrollIntoView({ 
          behavior: 'smooth', 
          block: 'start' 
        })
      }
    }, 100)
  }

  const handleRiskDisclosureClick = () => {
    navigate('/RiskDisclosure')
  }

  const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    const files = event.target.files
    if (!files || files.length === 0) return

    setIsUploading(true)
    const newImages: string[] = []
    const newResults: UploadResult[] = []
    const maxFiles = Math.min(files.length, 9 - uploadedImages.length)

    for (let i = 0; i < maxFiles; i++) {
      const file = files[i]
      const currentIndex = uploadedImages.length + i

      try {
        // 先显示本地预览
        const reader = new FileReader()
        reader.onload = (e) => {
          if (e.target?.result) {
            const imageData = e.target.result as string
            console.log(`图片 ${i + 1} 预览数据长度:`, imageData.length)
            newImages.push(imageData)
            if (newImages.length === maxFiles) {
              console.log('所有图片预览完成，设置到状态:', newImages.length)
              setUploadedImages([...uploadedImages, ...newImages])
            }
          }
        }
        reader.readAsDataURL(file)

        // 创建上传控制器
        const fileName = generateFileName(file.name)
        const objectKey = `medical-images/${fileName}`
        const controller = new UploadController(objectKey)
        setUploadControllers(prev => ({
          ...prev,
          [currentIndex]: controller
        }))

        // 上传到OSS
        const result = await uploadSingleFile(file, (status) => {
          // 检查是否已取消
          if (controller.isCancelledState) {
            return
          }
          
          setUploadStatuses(prev => ({
            ...prev,
            [currentIndex]: status
          }))
          
          // 如果有错误，记录错误信息
          if (status.error) {
            setUploadErrors(prev => ({
              ...prev,
              [currentIndex]: status.error!
            }))
          }
        })

        newResults.push(result)

        if (result.success) {
          setUploadSuccessCount(prev => prev + 1)
          console.log(`文件 ${file.name} 上传成功:`, result.url)
        } else {
          console.error(`文件 ${file.name} 上传失败:`, result.error)
        }
      } catch (error) {
        console.error(`文件 ${file.name} 上传异常:`, error)
        newResults.push({
          success: false,
          error: error instanceof Error ? error.message : '上传失败'
        })
      }
    }

    setUploadResults([...uploadResults, ...newResults])
    setIsUploading(false)
    
    // 清除状态
    setTimeout(() => {
      setUploadStatuses({})
      setUploadErrors({})
      setUploadControllers({})
    }, 3000)
  }

  const handleConfirm = () => {
    // 获取成功上传的图片URL
    const successfulUploads = uploadResults.filter(result => result.success)
    const uploadedImageUrls = successfulUploads.map(result => result.url).filter(Boolean) as string[]
    
    console.log('=== 确认提交调试信息 ===')
    console.log('上传的图片数量:', uploadedImages.length)
    console.log('上传的图片数据:', uploadedImages.map((img, i) => ({
      index: i,
      dataLength: img?.length,
      dataStart: img?.substring(0, 50) + '...'
    })))
    console.log('上传结果:', uploadResults)
    console.log('成功上传的文件URL:', uploadedImageUrls)
    
    // 添加用户图片消息到聊天 - 使用本地预览图片确保显示
    if (uploadedImages.length > 0) {
      const imageMessage = {
        id: `image_${Date.now()}`,
        type: 'user' as const,
        content: '我上传了以下图片资料',
        images: uploadedImages, // 使用本地预览的base64数据
        timestamp: Date.now()
      }
      
      console.log('准备添加到聊天的消息:', imageMessage)
      
      setChatMessages(prev => [...prev, imageMessage])
      
      // 隐藏上传区域，显示文件选择界面
      setShowUploadSection(false)
      setShowFileSelection(true)
      
      // 滚动到聊天底部
      setTimeout(() => {
        if (chatContainerRef.current) {
          chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight
        }
      }, 100)
      
      // 添加医生回复消息
      setTimeout(() => {
        const doctorReply = {
          id: `doctor_reply_${Date.now()}`,
          type: 'doctor' as const,
          content: '请问您想为以下哪位患者咨询？',
          timestamp: Date.now()
        }
        setChatMessages(prev => [...prev, doctorReply])
        
        // 再次滚动到底部
        setTimeout(() => {
          if (chatContainerRef.current) {
            chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight
          }
        }, 100)
      }, 1000)
    }
    
    // 显示上传成功提示
    if (uploadSuccessCount > 0) {
      alert(`成功上传 ${uploadSuccessCount} 张图片！`)
    }
  }

  const handleSkip = () => {
    // 添加"暂无图片"消息
    const noImageMessage = {
      id: `no_image_${Date.now()}`,
      type: 'user' as const,
      content: '暂无图片',
      timestamp: Date.now()
    }
    setChatMessages(prev => [...prev, noImageMessage])
    
    // 隐藏上传区域，显示文件选择界面
    setShowUploadSection(false)
    setShowFileSelection(true)
    
    // 滚动到聊天底部
    setTimeout(() => {
      if (chatContainerRef.current) {
        chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight
      }
    }, 100)
    
    // 添加医生回复消息
    setTimeout(() => {
      const doctorReply = {
        id: `doctor_reply_${Date.now()}`,
        type: 'doctor' as const,
        content: '请问您想为以下哪位患者咨询？',
        timestamp: Date.now()
      }
      setChatMessages(prev => [...prev, doctorReply])
      
      // 再次滚动到底部
      setTimeout(() => {
        if (chatContainerRef.current) {
          chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight
        }
      }, 100)
    }, 1000)
  }


  const handleSelectArchive = (archiveId: string) => {
    // 设置当前选中的档案ID
    setCurrentSelectedArchiveId(archiveId)
    dispatch(selectArchive(archiveId))
    
    // 获取选中的档案信息
    const selectedArchive = archivesList.find(archive => archive.id === archiveId)
    if (selectedArchive) {
      // 计算年龄
      const birthYear = new Date(selectedArchive.birthDate).getFullYear()
      const currentYear = new Date().getFullYear()
      const age = currentYear - birthYear
      
      // 格式化手机号（隐藏中间4位）
      const phone = selectedArchive.temphone
      const maskedPhone = phone.length === 11 ? 
        phone.substring(0, 4) + '****' + phone.substring(7) : 
        phone
      
      // 创建档案信息消息
      const archiveMessage = {
        id: `archive_${Date.now()}`,
        type: 'user' as const,
        content: `我选择为 ${selectedArchive.name}(${selectedArchive.relationship || '其他'}) 咨询`,
        timestamp: Date.now()
      }
      
      // 添加档案信息到聊天消息
      setChatMessages(prev => [...prev, archiveMessage])
      
      // 添加档案详细信息到聊天消息
      const archiveDetailMessage = {
        id: `archive_detail_${Date.now()}`,
        type: 'user' as const,
        content: `患者信息：${age}岁 ${selectedArchive.set} ${maskedPhone}`,
        timestamp: Date.now()
      }
      
      setChatMessages(prev => [...prev, archiveDetailMessage])
      
      // 隐藏档案选择界面
      setShowFileSelection(false)
      
      // 滚动到聊天底部
      setTimeout(() => {
        if (chatContainerRef.current) {
          chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight
        }
      }, 100)
      
      // 添加医生回复消息
      setTimeout(() => {
        const doctorReply = {
          id: `doctor_reply_${Date.now()}`,
          type: 'doctor' as const,
          content: '好的，我已经了解了患者的基本信息。请详细描述患者的症状和病情，以便我为您提供更准确的医疗建议。',
          timestamp: Date.now()
        }
        setChatMessages(prev => [...prev, doctorReply])
        
        // 立即显示分诊结果和推荐服务
        setShowTriageResult(true)
        setShowRecommendations(true)
        
        // 再次滚动到底部
        setTimeout(() => {
          if (chatContainerRef.current) {
            chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight
          }
        }, 100)
      }, 1000)
    }
    
    console.log('选择了档案:', archiveId)
  }

  // const handleRemoveArchive = (archiveId: string) => {
  //   dispatch(removeArchiveFromList(archiveId))
  //   console.log('删除了档案:', archiveId)
  // }

  const handleNewFile = () => {
    navigate('/NewOrder')
  }

  const handleCancelUpload = async (index: number) => {
    const controller = uploadControllers[index]
    if (controller) {
      const success = await controller.cancel()
      if (success) {
        // 移除该图片
        setUploadedImages(uploadedImages.filter((_, i) => i !== index))
        setUploadResults(uploadResults.filter((_, i) => i !== index))
        setUploadStatuses(prev => {
          const newStatuses = { ...prev }
          delete newStatuses[index]
          return newStatuses
        })
        setUploadErrors(prev => {
          const newErrors = { ...prev }
          delete newErrors[index]
          return newErrors
        })
        setUploadControllers(prev => {
          const newControllers = { ...prev }
          delete newControllers[index]
          return newControllers
        })
        console.log(`已取消上传图片 ${index + 1}`)
      }
    }
  }

  const progressSteps = [
    { label: '描述病情', active: true },
    { label: '匹配医生', active: false },
    { label: '开始咨询', active: false }
  ]

  return (
    <div className={styles.pageContainer}>
      {/* 头部导航栏（包含进度条） */}
      <Navbar 
        title="描述病情" 
        showBack={true} 
        onBack={handleBack}
        progressSteps={progressSteps}
      />

      {/* 服务保障 */}
      <div className={styles.serviceGuarantee}>
        <div className={styles.guaranteeTitle}>
          <span className={styles.shieldIcon}>🛡️</span>
          服务保障
        </div>
        <div className={styles.guaranteeList}>
          <div className={styles.guaranteeItem}>专业医生</div>
          <div className={styles.guaranteeItem}>实名认证</div>
          <div className={styles.guaranteeItem}>多轮沟通</div>
          <div className={styles.guaranteeItem}>超时退款</div>
        </div>
      </div>

      {/* 风险告知 */}
      <div className={styles.disclaimer}>
        <div className={styles.disclaimerText}>
          请您仔细阅读
          <span 
            className={styles.disclaimerLink}
            onClick={handleRiskDisclosureClick}
            style={{ cursor: 'pointer' }}
          >
            《风险告知及患者知情同意书》
          </span>
          ,如非复诊,我们仅提供医疗咨询服务。继续操作表示您知悉并同意上述告知内容。
        </div>
      </div>

      {/* 聊天界面 */}
      <div ref={chatContainerRef} className={`${styles.chatContainer} ${showFileSelection ? styles.withFileSelection : ''}`}>
        {/* 初始医生消息 */}
        <div className={styles.chatMessage}>
          <img 
            src="/photo103.jpg" 
            alt="医生助手" 
            className={styles.doctorAvatar}
          />
          <div className={styles.messageBubble}>
            您好,我是您的医生助手。
          </div>
        </div>
        
        <div className={styles.chatMessage}>
          <img 
            src="/photo103.jpg" 
            alt="医生助手" 
            className={styles.doctorAvatar}
          />
          <div className={styles.messageBubble}>
            请在下方输入框详细描述病情,以便医生准确了解您的情况,快速接诊
          </div>

          
        </div>



        {/* 医生回复消息 */}
        {isSubmitted && (
          <div className={styles.chatMessage}>
            <img 
              src="/photo103.jpg" 
              alt="医生助手" 
              className={styles.doctorAvatar}
            />
            <div className={styles.messageBubble}>
              请上传能反应患者病情的相关资料,上传的资料仅自己和医生可见。
            </div>
          </div>
        )}

        {/* 动态聊天消息 */}
        {(() => {
          console.log('当前聊天消息数量:', chatMessages.length)
          return null
        })()}
        {chatMessages.map((message) => {
          console.log('渲染消息:', message)
          return (
            <div key={message.id}>
              {message.type === 'user' ? (
                <div className={styles.userMessage}>
                  <div className={styles.userMessageBubble}>
                    <div className={styles.messageText}>{message.content}</div>
                    {message.images && message.images.length > 0 && (
                      <div className={styles.messageImages}>
                        {message.images.map((imageUrl, index) => {
                          console.log(`聊天中显示图片 ${index + 1}:`, imageUrl?.substring(0, 50) + '...')
                          return (
                            <img 
                              key={index}
                              src={imageUrl} 
                              alt={`上传图片${index + 1}`}
                              className={styles.messageImage}
                              onClick={() => setSelectedImage(imageUrl)}
                              onError={(e) => {
                                console.error(`图片 ${index + 1} 加载失败:`, imageUrl)
                                console.error('错误详情:', e)
                              }}
                              onLoad={() => {
                                console.log(`图片 ${index + 1} 加载成功`)
                              }}
                            />
                          )
                        })}
                      </div>
                    )}
                  </div>
                  <div className={styles.userAvatar}>
                    <div className={styles.userAvatarIcon}>👤</div>
                  </div>
                </div>
              ) : (
                <div className={styles.chatMessage}>
                  <img 
                    src="/photo103.jpg" 
                    alt="医生助手" 
                    className={styles.doctorAvatar}
                  />
                  <div className={styles.messageBubble}>
                    {message.content}
                  </div>
                </div>
              )}
            </div>
          )
        })}
      </div>

      {/* 上传图片界面 */}
      {isSubmitted && showUploadSection && (
        <div ref={uploadContainerRef} className={styles.uploadContainer}>
          <div className={styles.uploadHeader}>
            <h3 className={styles.uploadTitle}>上传图片 (选填)</h3>
            <span className={styles.skipButton} onClick={handleSkip}>跳过</span>
          </div>
          <div className={styles.uploadSubtitle}>
            检查单/历史病例/患处照片 (最多9张)
          </div>
           <div className={styles.uploadArea}>
             <div className={styles.uploadGrid}>
               {uploadedImages.map((image, index) => (
                 <div key={index} className={styles.uploadedImage}>
                   <img 
                     src={image} 
                     alt={`上传图片${index + 1}`}
                     onError={(e) => {
                       console.error(`上传区域图片 ${index + 1} 加载失败:`, image?.substring(0, 50) + '...')
                       console.error('错误详情:', e)
                     }}
                     onLoad={() => {
                       console.log(`上传区域图片 ${index + 1} 加载成功`)
                     }}
                   />
                   {/* 上传进度显示 */}
                   {uploadStatuses[index] && uploadStatuses[index].isUploading && (
                     <div className={styles.uploadProgress}>
                       <div className={styles.progressBar}>
                         <div 
                           className={styles.progressFill}
                           style={{ width: `${uploadStatuses[index].progress}%` }}
                         ></div>
                       </div>
                       <div className={styles.progressInfo}>
                         <span className={styles.progressText}>{uploadStatuses[index].progress}%</span>
                         {uploadStatuses[index].speed > 0 && (
                           <span className={styles.speedText}>
                             {(uploadStatuses[index].speed / 1024).toFixed(1)} KB/s
                           </span>
                         )}
                         {uploadStatuses[index].remainingTime > 0 && (
                           <span className={styles.timeText}>
                             剩余 {Math.round(uploadStatuses[index].remainingTime)}s
                           </span>
                         )}
                       </div>
                     </div>
                   )}
                   
                   {/* 错误信息显示 */}
                   {uploadErrors[index] && (
                     <div className={styles.uploadError}>
                       <span className={styles.errorText}>{uploadErrors[index]}</span>
                     </div>
                   )}
                   {/* 上传成功/失败状态 */}
                   {uploadResults[index] && (
                     <div className={`${styles.uploadStatus} ${
                       uploadResults[index].success ? styles.success : styles.error
                     }`}>
                       {uploadResults[index].success ? '✓' : '✗'}
                     </div>
                   )}
                   <button 
                     className={styles.removeImage}
                     onClick={async () => {
                       // 如果正在上传，先取消上传
                       if (uploadStatuses[index]?.isUploading) {
                         await handleCancelUpload(index)
                       } else {
                         // 直接删除
                         setUploadedImages(uploadedImages.filter((_, i) => i !== index))
                         setUploadResults(uploadResults.filter((_, i) => i !== index))
                         setUploadStatuses(prev => {
                           const newStatuses = { ...prev }
                           delete newStatuses[index]
                           return newStatuses
                         })
                         setUploadErrors(prev => {
                           const newErrors = { ...prev }
                           delete newErrors[index]
                           return newErrors
                         })
                         setUploadControllers(prev => {
                           const newControllers = { ...prev }
                           delete newControllers[index]
                           return newControllers
                         })
                       }
                     }}
                   >
                     {uploadStatuses[index]?.isUploading ? '⏹' : '×'}
                   </button>
                 </div>
               ))}
               {uploadedImages.length < 9 && (
                 <div className={styles.uploadButton}>
                   <input
                     type="file"
                     accept="image/*"
                     multiple
                     onChange={handleImageUpload}
                     className={styles.fileInput}
                     disabled={isUploading}
                   />
                   <div className={styles.uploadIcon}>
                     {isUploading ? '⏳' : '+'}
                   </div>
                 </div>
               )}
             </div>
             {/* 上传状态提示 */}
             {isUploading && (
               <div className={styles.uploadingTip}>
                 <div className={styles.uploadingIcon}>⏳</div>
                 <div className={styles.uploadingText}>
                   <div>正在上传图片，请稍候...</div>
                   <div className={styles.uploadingSubtext}>
                     支持大文件分片上传，网络中断可自动重试
                   </div>
                 </div>
               </div>
             )}
             
             {/* 上传成功统计 */}
             {uploadSuccessCount > 0 && !isUploading && (
               <div className={styles.uploadSuccessTip}>
                 <div className={styles.successIcon}>✅</div>
                 <div className={styles.successText}>
                   已成功上传 {uploadSuccessCount} 张图片
                 </div>
               </div>
             )}
             
             {/* 上传错误统计 */}
             {Object.keys(uploadErrors).length > 0 && !isUploading && (
               <div className={styles.uploadErrorTip}>
                 <div className={styles.errorIcon}>❌</div>
                 <div className={styles.errorText}>
                   有 {Object.keys(uploadErrors).length} 张图片上传失败，请检查网络连接后重试
                 </div>
               </div>
             )}
           </div>
        </div>
      )}

      {/* 输入区域 */}
      {!isSubmitted && (
        <div className={styles.inputContainer}>
          <textarea
            className={styles.inputField}
            placeholder="请用5-500字描述具体症状、患病时长、用药情况、需要医生提供哪些帮助等, 以便医生更好帮助您解决问题。"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            rows={3}
          />
          <button 
            className={styles.submitButton}
            onClick={handleSubmit}
            disabled={inputValue.trim().length < 5}
          >
            提交
          </button>
        </div>
      )}

      {/* 确认按钮 */}
      {isSubmitted && showUploadSection && (
        <div className={styles.confirmContainer}>
          <button 
            className={styles.confirmButton}
            onClick={handleConfirm}
          >
            确定
          </button>
        </div>
      )}

      {/* 分诊结果 */}
      {showTriageResult && (
        <div className={styles.triageResult}>
          <div className={styles.triageInfo}>
            <span className={styles.triageText}>根据您的描述 为您分诊到</span>
            <span className={styles.departmentName}>【全科】</span>
          </div>
          <div className={styles.reselectButton}>
            <span className={styles.reselectIcon}>↻</span>
            <span>重选科室</span>
          </div>
        </div>
      )}

      {/* 推荐服务 */}
      {showRecommendations && (
        <div className={styles.recommendations}>
          <div className={styles.recommendationsHeader}>
            <h3 className={styles.recommendationsTitle}>为你推荐</h3>
            <p className={styles.recommendationsSubtitle}>智能匹配医生·未接诊可退款</p>
          </div>
          
          <div className={styles.serviceList}>
            {/* 极速图文问诊 */}
            <div className={styles.serviceItem}>
              <div className={styles.serviceIcon}>
                <div className={styles.iconChat}>💬</div>
              </div>
              <div className={styles.serviceInfo}>
                <div className={styles.serviceName}>
                  极速图文问诊
                  <span className={styles.recommendedTag}>推荐</span>
                </div>
                <div className={styles.serviceDesc}>平均3分钟接诊,交流时长:30条消息/30分钟</div>
              </div>
              <div className={styles.servicePrice}>
                <span className={styles.originalPrice}>¥9.9</span>
                <span className={styles.currentPrice}>¥6.9</span>
                <span className={styles.arrow}>›</span>
              </div>
            </div>

            {/* 极速电话问诊 */}
            <div className={styles.serviceItem}>
              <div className={styles.serviceIcon}>
                <div className={styles.iconPhone}>📞</div>
              </div>
              <div className={styles.serviceInfo}>
                <div className={styles.serviceName}>极速电话问诊</div>
                <div className={styles.serviceDesc}>平均10分钟响应,通话时长:10分钟</div>
              </div>
              <div className={styles.servicePrice}>
                <span className={styles.originalPrice}>¥59.9</span>
                <span className={styles.currentPrice}>¥30</span>
                <span className={styles.arrow}>›</span>
              </div>
            </div>

            {/* 极速视频问诊 */}
            <div className={styles.serviceItem}>
              <div className={styles.serviceIcon}>
                <div className={styles.iconVideo}>📹</div>
              </div>
              <div className={styles.serviceInfo}>
                <div className={styles.serviceName}>极速视频问诊</div>
                <div className={styles.serviceDesc}>平均10分钟响应,通话时长:15分钟</div>
              </div>
              <div className={styles.servicePrice}>
                <span className={styles.originalPrice}>¥99.9</span>
                <span className={styles.currentPrice}>¥50</span>
                <span className={styles.arrow}>›</span>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* 文件选择界面 */}
      {showFileSelection && (
        <div className={styles.fileSelectionContainer}>
          <div className={styles.fileSelectionHeader}>
            <h3>选择档案</h3>
            <span className={styles.newFileText} onClick={handleNewFile}>
              + 新建档案
            </span>
          </div>
          
          <div className={styles.archivesList}>
            {archivesList.map((archive) => {
              // 计算年龄
              const birthYear = new Date(archive.birthDate).getFullYear()
              const currentYear = new Date().getFullYear()
              const age = currentYear - birthYear
              
              // 格式化手机号（隐藏中间4位）
              const phone = archive.temphone
              const maskedPhone = phone.length === 11 ? 
                phone.substring(0, 4) + '****' + phone.substring(7) : 
                phone
              
              return (
                <div 
                  key={archive.id} 
                  className={`${styles.archiveCard} ${
                    currentSelectedArchiveId === archive.id ? styles.selected : ''
                  }`}
                  onClick={() => handleSelectArchive(archive.id!)}
                >
                  <div className={styles.archiveInfo}>
                    <div className={styles.archiveName}>
                      {archive.name}
                      <span className={styles.archiveRelationship}>({archive.relationship || '其他'})</span>
                    </div>
                    <div className={styles.archiveDetails}>
                      {age} {archive.set} {maskedPhone}
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        </div>
      )}

      {/* 图片预览模态框 */}
      {selectedImage && (
        <div className={styles.imageModal} onClick={() => setSelectedImage(null)}>
          <div className={styles.imageModalContent} onClick={(e) => e.stopPropagation()}>
            <img 
              src={selectedImage} 
              alt="预览图片" 
              className={styles.previewImage}
            />
            <button 
              className={styles.closeButton}
              onClick={() => setSelectedImage(null)}
            >
              ×
            </button>
          </div>
        </div>
      )}
    </div>
  )
}

export default Index
